﻿using System;
using System.Linq;
using System.Reflection;
using System.Windows;

namespace EnsureWeb.UI.Core
{
    public class ViewModelManager
    {
        private static Application app = Application.Current;

        public static void InjectViewModelsToResources()
        {
            Assembly executingAssembly = Assembly.GetCallingAssembly();
            foreach (Type type in executingAssembly.GetTypes())
            {
                var attributes = type.GetCustomAttributes(false);

                foreach (var attribute in attributes)
                {
                    if (attribute is StaticResourceAttribute)
                    {
                        var obj = Activator.CreateInstance(type);
                        if (!app.Resources.Contains(type.Name))
                            app.Resources.Add(type.Name, obj);
                    }
                }
            }
        }

        public static T GetViewModelFromResources<T>()
        {
            var key = typeof(T).Name;
            if (app.Resources.Contains(key))
                return (T)app.Resources[key];
            else
                return default(T);
        }
    }
}
